﻿using System;
using WebFormsMvp.Contrib.Data.Services;
using WebFormsMvp.Contrib.Views;

namespace WebFormsMvp.Contrib.Presenters
{
    /// <summary>
    /// Presenter which provides authentication of an account via the <see cref="WebFormsMvp.Contrib.Data.Services.IAuthenticationService"/>
    /// </summary>
    /// <remarks>
    /// <para>
    ///     This presenter would need to be inherited from unless the instance of <see cref="WebFormsMvp.Binder.IPresenterFactory"/> 
    ///     used injects the <see cref="WebFormsMvp.Contrib.Data.Services.IAuthenticationService"/>.
    /// </para>
    /// <seealso cref="WebFormsMvp.Presenter{TView}"/>
    /// </remarks>
    public class AuthenticationPresenter : Presenter<IAuthenticationView>
    {
        /// <summary>
        /// The instance of the <see cref="WebFormsMvp.Contrib.Data.Services.IAuthenticationService"/> for this presenter
        /// </summary>
        protected IAuthenticationService dataService;

        /// <summary>
        /// Initializes a new instance of the <see cref="AuthenticationPresenter"/> class.
        /// </summary>
        /// <param name="view">The view required for this presenter.</param>
        /// <param name="dataService">The data service required for this presenter.</param>
        public AuthenticationPresenter(IAuthenticationView view, IAuthenticationService dataService) : base(view)
        {
            this.dataService = dataService;
            view.Load += new EventHandler(View_Load);
            view.Submit += new EventHandler<AuthenticationEventArgs>(View_Submit);
        }

        /// <summary>
        /// Handles the Submit (Authentication) event of the View control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="WebFormsMvp.Contrib.Views.AuthenticationEventArgs"/> instance containing the event data.</param>
        protected virtual void View_Submit(object sender, AuthenticationEventArgs e)
        {
            this.View.Model.IsAuthenticated = this.dataService.LogIn(e.Username, e.Password);
        }

        /// <summary>
        /// Handles the Load event of the View control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected virtual void View_Load(object sender, EventArgs e) { }

        /// <summary>
        /// Releases the view.
        /// </summary>
        public override void ReleaseView()
        {
            this.View.Load -= new EventHandler(this.View_Load);
            this.View.Submit -= new EventHandler<AuthenticationEventArgs>(this.View_Submit);
        }
    }
}
